

package top.continew.admin.question.manger.service.scheduled;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.continew.admin.question.mapper.UserQuestionInfoMapper;
import top.continew.admin.question.mapper.test.TestMapper;
import top.continew.admin.question.model.QuestionSetInfo;
import top.continew.admin.question.model.UserQuestion;
import top.continew.admin.question.model.UserQuestionInfo;
import top.continew.admin.question.model.question.Question;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class Task {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TestMapper testMapper;

    @Autowired
    private UserQuestionInfoMapper userQuestionInfoMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    //    @Scheduled(cron = "*/15 * * * * ?")
    public void executeTestQuestion() {
        List<QuestionSetInfo> questionSetInfos = new QuestionSetInfo().selectAll();
        for (QuestionSetInfo questionSetInfo : questionSetInfos) {
            handleQuestion(questionSetInfo);
        }

    }

    private void handleQuestion(QuestionSetInfo questionSetInfo) {
        List<UserQuestionInfo> userQuestionInfo = List.of();
        if (questionSetInfo.getType().equals("1")) {
            userQuestionInfo = handleTestQuestion(questionSetInfo);
        }
        saveUserQuestionInfo(userQuestionInfo);
    }

    private void saveUserQuestionInfo(List<UserQuestionInfo> userQuestionInfo) {
        if (!userQuestionInfo.isEmpty()) {
            for (UserQuestionInfo questionInfo : userQuestionInfo) {
                UserQuestionInfo old = new UserQuestionInfo().selectOne(new QueryWrapper<UserQuestionInfo>()
                    .eq("questionInfoId", questionInfo.getQuestionInfoId())
                    .eq("userId", questionInfo.getUserId()));
                if (old != null) {
                    questionInfo.setId(old.getId());
                }
                questionInfo.insertOrUpdate();

            }
        }
    }

    /**
     * 考试
     */
    private List<UserQuestionInfo> handleTestQuestion(QuestionSetInfo questionSetInfo) {
        //获取客观题题目及答案
        List<Question> question = testMapper.queryObjectiveQuestion(questionSetInfo.getTypeId());
        Map<Long, List<Question>> questionMap = question.stream().collect(Collectors.groupingBy(Question::getId));
        //获取学员答案
        List<UserQuestion> userQuestions = userQuestionInfoMapper.queryUserTest(questionSetInfo.getTypeId());
        return handleQuestionRes(questionMap, userQuestions, questionSetInfo);
    }

    /**
     * 组装计算数据
     */
    private List<UserQuestionInfo> handleQuestionRes(Map<Long, List<Question>> questionMap,
                                                     List<UserQuestion> userQuestions,
                                                     QuestionSetInfo questionSetInfo) {

        //对比计算学员数据
        List<UserQuestionInfo> userQuestionInfos = new ArrayList<>();
        for (UserQuestion userQuestion : userQuestions) {
            JSONObject map = JSON.parseObject(userQuestion.getAnswer());
            if (map == null || map.size() == 0) {
                continue;
            }
            UserQuestionInfo userQuestionInfo = new UserQuestionInfo();
            userQuestionInfo.setQuestionInfoId(questionSetInfo.getId());
            userQuestionInfo.setCompleteSum(String.valueOf(map.size()));
            userQuestionInfo.setBeginTime(userQuestion.getCtime());
            userQuestionInfo.setCompleteInterestRate(calculationRate(map.size(), questionSetInfo.getSum()));
            int trueSum = 0;
            for (String qid : map.keySet()) {
                List<Question> res = questionMap.getOrDefault(Long.parseLong(qid), new ArrayList<>());
                if (res.size() > 0) {
                    //判断题目正确性
                    if (questionIsTrue(res.get(0).getAnswer(), String.valueOf(map.get(qid)), res.get(0).getType())) {
                        trueSum++;
                    }
                } else {
                    trueSum++;
                }
            }
            userQuestionInfo.setUserId(userQuestion.getUid());
            userQuestionInfo.setTrueSum(String.valueOf(trueSum));
            userQuestionInfo.setTrueInterestRate(calculationRate(trueSum, userQuestionInfo.getCompleteSum()));
            userQuestionInfos.add(userQuestionInfo);
        }
        return userQuestionInfos;
    }

    /**
     * 判断题目正确性
     */
    private boolean questionIsTrue(String questionAnswer, String userAnswer, Long type) {
        return setUserAnswer(userAnswer).equals(setQuestionAnswer(questionAnswer));
    }

    /***
     * 预处理用户答案
     */
    private String setUserAnswer(String userAnswer) {
        if (userAnswer.contains(",")) {
            List<String> userAnswerList = Arrays.stream(userAnswer.split(",")).sorted().collect(Collectors.toList());
            return String.join(",", userAnswerList);
        } else {
            StringBuilder userAnswerStr = new StringBuilder();
            char[] userAnswerArrays = userAnswer.toCharArray();
            Arrays.sort(userAnswerArrays);
            for (int i = 0; i < userAnswerArrays.length; i++) {
                userAnswerStr.append(userAnswerArrays[i]);
                if (i + 1 < userAnswerArrays.length) {
                    userAnswerStr.append(",");
                }
            }
            return userAnswerStr.toString();
        }
    }

    /**
     * 预处理题目答案
     */
    private String setQuestionAnswer(String questionAnswer) {
        questionAnswer = questionAnswer.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\\"", "");
        if (questionAnswer.contains(",")) {
            List<String> questionAnswerList = Arrays.stream(questionAnswer.split(","))
                .sorted()
                .collect(Collectors.toList());
            return String.join(",", questionAnswerList);
        } else {
            StringBuilder questionAnswerStr = new StringBuilder();
            char[] questionAnswerArrays = questionAnswer.toCharArray();
            Arrays.sort(questionAnswerArrays);
            for (int i = 0; i < questionAnswerArrays.length; i++) {
                questionAnswerStr.append(questionAnswerArrays[i]);
                if (i + 1 < questionAnswerArrays.length) {
                    questionAnswerStr.append(",");
                }
            }
            return questionAnswerStr.toString();
        }
    }

    //计算百分比
    private String calculationRate(int size, String sum) {
        if (sum.equals("0") || StrUtil.isEmpty(sum)) {
            return "0";
        }
        BigDecimal divisor = BigDecimal.valueOf(size);
        BigDecimal dividend = BigDecimal.valueOf(Long.parseLong(sum));
        return String.valueOf(divisor.divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
    }

}
